
import models, constants
import cgi,datetime,logging,sys
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

logging.basicConfig(level=logging.DEBUG)

class Click(webapp.RequestHandler):
    def get(self):
        layer = int(self.request.get('layer'))
        x     = float(self.request.get('x'))
        y     = float(self.request.get('y'))
        box_x = x * constants.MAP_TOP_LAYER_WIDTH  * (2 ** layer) / constants.BOUNDING_BOX_WIDTH
        box_y = y * constants.MAP_TOP_LAYER_HEIGHT * (2 ** layer) / constants.BOUNDING_BOX_HEIGHT

        query_str = "SELECT * FROM Node WHERE layer = :layer and box_x = :x and box_y = :y" 
        datum = db.GqlQuery(query_str, layer=layer, x=int(box_x), y=int(box_y))
        res = "var node=null"
        min_d = 1.0
        for data in datum:
            d = ((data.x - x) ** 2 + (data.y - y) ** 2)
            if d < min_d:
                min_d = d
                res = "var node={id:'%s', label:'%s', is_browse_node:%d};" % (data.id_str, data.label, data.is_browse_node)
        self.response.out.write(res)


# WSGI
application = webapp.WSGIApplication([
        ('/event_click', Click),
        ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
